package com.xw.controller.manage;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.xw.common.Const;
import com.xw.model.DicGroup;
import com.xw.model.DicGroupLimit;
import com.xw.model.DicLimit;
import com.xw.service.sysconfig.DicGroupLimitService;
import com.xw.service.sysconfig.DicGroupService;
import com.xw.service.sysconfig.DicLimitService;
import com.xw.util.AppUtil;
import com.xw.vo.LimitVo;
import com.xw.vo.ZTree;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 角色
 */
@Controller
@RequestMapping("/manage/group")
@Scope("prototype")
public class GroupController {
    Map<String,Object> map=null;

    @Resource
    private DicGroupService groupService;
    @Resource
    private DicLimitService limitService;
    @Resource
    private DicGroupLimitService groupLimitService;

    /**
     * 跳转页面到数据列表页
     * @param request
     * @return
     */
    @RequestMapping(value = "/findAll")
    public String findAll(HttpServletRequest request,  String glId){
        DicGroupLimit model = groupLimitService.queryByUUID(glId);
        request.setAttribute("model",model);
        return "group/list";
    }

    /**
     * 跳转到添加角色页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/goAdd")
    public String goAdd(HttpServletRequest request){
        //获取所有权限
        List<DicLimit> list = limitService.queryAll();
        request.setAttribute("kitList",list);
        return "group/add";
    }

    /**
     * 跳转到修改角色页面
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/goEdit")
    public String goEdit(HttpServletRequest request,String id){
        DicGroup group = groupService.queryByUUID(id);

        List<DicLimit> limits = limitService.queryAll();

        List<DicGroupLimit> groupLimitList=groupLimitService.findListByGroupId(id);

        // 遍历，获取新的对象集合
        List<LimitVo> limitVos = new ArrayList<LimitVo>();

        for(int i=0; i<limits.size(); i++){
            LimitVo limitVo = new LimitVo();
            limitVo.setLimit(limits.get(i));

            for(int j=0; j<groupLimitList.size(); j++){
                if(groupLimitList.get(j).getLimitId().equals(limits.get(i).getLimitId())){
                    limitVo.setType(1);
                    limitVo.setC(groupLimitList.get(j).getGlCreate());
                    limitVo.setR(groupLimitList.get(j).getGlRetrieve());
                    limitVo.setU(groupLimitList.get(j).getGlUpdate());
                    limitVo.setD(groupLimitList.get(j).getGlDelete());
                }
            }
            limitVos.add(limitVo);
        }

        request.setAttribute("kitList",limitVos);
        request.setAttribute("kitModel",group);
        return "group/edit";
    }


    /**
     * 根据条件搜索角色
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/findAllJson",method = RequestMethod.GET)
    @ResponseBody
    public Object findAllJson(HttpServletRequest request,DicGroup model,Integer page,Integer limit){
        map = new HashMap<>();
        String groupName = request.getParameter("groupName");

        if (StrUtil.isNotEmpty(groupName)){
            model.setGroupName(groupName);
        }
        //总条数
        Integer count = groupService.findByWhere(model).size();

        if (page != null && limit != null) {
            PageHelper.startPage(page,limit,false);
        }
        List<DicGroup> list = groupService.findByWhere(model);

        map.put("code",0);
        map.put("msg","");
        map.put("data",list);
        map.put("count",count);
        return map;
    }

    /**
     * 添加角色
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Object add(HttpServletRequest request,DicGroup model){
        map = new HashMap<>();
        //判断名称是否已存在
        DicGroup group = new DicGroup();
        group.setGroupName(model.getGroupName());
        Integer num = groupService.queryCount(group);
        if (num>0){
            map.put("code",101);
            map.put("msg","The group name already exists");
//            map.put("msg","分组名称已存在");
            return JSONObject.toJSON(map);
        }
        model.setGroupId(AppUtil.uuid());
        Integer integer = groupService.saveSelect(model);
        if (integer>0){
            /*添加角色权限*/
            addGroupLimit(request, model);
            map.put("code",200);
            map.put("msg", Const.OPREATE_MSG_SUCCESS);
        }else{
            map.put("code",101);
            map.put("msg",Const.OPREATE_MSG_ERROR);
        }
        return map;
    }


    /**
     * 修改角色
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public Object edit(HttpServletRequest request,DicGroup model){
        map = new HashMap<>();
        /*
           根据id查询分组对象，判断分组名称和数据库中是否改变
           没有改变就不需要判断名称是否重复，否则就要匹配是否存在相同的分组（角色）名
        */
        DicGroup dicGroup = groupService.queryByUUID(model.getGroupId());
        if (model.getGroupName().equals(dicGroup.getGroupName())){
            /*
                名称相同，先删除分组关联的权限
                再重新保存分组的权限
             */
            groupLimitService.delByGroupId(model.getGroupId());
            addGroupLimit(request,dicGroup);
            map.put("code",200);
            map.put("msg",Const.OPREATE_MSG_SUCCESS);
        }else{
            /*
            * 名称不同，先判断是否重名*/
            DicGroup group = new DicGroup();
            group.setGroupName(model.getGroupName());
            Integer num = groupService.queryCount(group);
            if (num>0){
                map.put("code",101);
                map.put("msg","The group name already exists");
//                map.put("msg","分组名称已存在");
                return JSONObject.toJSON(map);
            }
            /*
            * 不重名，保存分组对象
            * 然后保存分组权限*/
            Integer integer = groupService.updateSelective(model);
            if (integer>0){
                addGroupLimit(request,dicGroup);
                map.put("code",200);
                map.put("msg",Const.OPREATE_MSG_SUCCESS);
            }else{
                map.put("code",101);
                map.put("msg",Const.OPREATE_MSG_ERROR);
            }

        }




        return map;
    }

    /**
     * 根据主键删除分组
     * 多张表操作需要用到事务，放在service处理
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/del",method = RequestMethod.POST)
    @ResponseBody
    public Object del(HttpServletRequest request,String id){
        Map<String,Object> map = groupService.del(id);
        return map;
    }

    /**
     * 添加分组权限的方法
     * @param request
     * @param group
     */
    private void addGroupLimit(HttpServletRequest request, DicGroup group) {
        // 遍历权限
        Enumeration<String> paraNames=request.getParameterNames();
        for(Enumeration<String> e=paraNames;e.hasMoreElements();) {

            String thisName = e.nextElement().toString();  //  传来的key值
            String thisValue = request.getParameter(thisName);  //  传来的key值带的参数

            if (!"groupName".equals(thisName)) {
                // 根据 _ 切割 key 字符串
                String[] key = thisName.split("_");

                // 如果是一级类目
                if ("limitone".equals(key[0])) {
                    // 保存说明有这个权限，而且都有
                    DicGroupLimit gGroupLimit = new DicGroupLimit();
                    gGroupLimit.setGlId(AppUtil.uuid());
                    gGroupLimit.setGroupId(group.getGroupId());
                    gGroupLimit.setLimitId(thisValue);
                    gGroupLimit.setGlCreate(1);
                    gGroupLimit.setGlDelete(1);
                    gGroupLimit.setGlUpdate(1);
                    gGroupLimit.setGlRetrieve(1);
                    groupLimitService.saveSelect(gGroupLimit);
                }

                // 如果是二级类目
                if ("limittwo0".equals(key[0])) {
                    // 保存说明有这个权限，遍历查看有没有 crud
                    DicGroupLimit gGroupLimit = new DicGroupLimit();
                    gGroupLimit.setGlId(AppUtil.uuid());
                    gGroupLimit.setGroupId(group.getGroupId());
                    gGroupLimit.setLimitId(thisValue);

                    String c = request.getParameter("limittwo1_" + thisValue);
                    String r = request.getParameter("limittwo2_" + thisValue);
                    String u = request.getParameter("limittwo3_" + thisValue);
                    String d = request.getParameter("limittwo4_" + thisValue);

                    gGroupLimit.setGlCreate("1".equals(c) ? 1 : 2);
                    gGroupLimit.setGlRetrieve("1".equals(r) ? 1 : 2);
                    gGroupLimit.setGlUpdate("1".equals(u) ? 1 : 2);
                    gGroupLimit.setGlDelete("1".equals(d) ? 1 : 2);
                    groupLimitService.saveSelect(gGroupLimit);
                }
            }
        }
    }



    /**
     * 通过ztree渲染菜单
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/goGiveLimit")
    public String goGiveLimit(HttpServletRequest request,String id){
        DicGroup group = groupService.queryByUUID(id);
        //查询所有功能权限
        List<DicLimit> list = limitService.queryAll();
        List<ZTree> zTreeList = new ArrayList<>();
        for (DicLimit l:list){
            ZTree tree = new ZTree();
            tree.setId(l.getLimitId());
            tree.setName(l.getLimitName());
            tree.setpId(l.getLimitPid());
            zTreeList.add(tree);
        }
        request.setAttribute("model",group);
        request.setAttribute("list", new Gson().toJson(zTreeList));
        System.out.println(JSONObject.toJSONString(zTreeList));
        return "group/givelimit";
    }
}
